package com.api.demo.endpoint;

import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.stereotype.Component;

import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.api.demo.entity.ApiLog;
import com.api.demo.mapper.ApiLogMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

@Component
@Endpoint(id = "logstats")
public class LogStatsEndpoint {

    @Resource
    private ApiLogMapper apiLogMapper;

    @ReadOperation
    public Map<String, Object> stats() {
        Map<String, Object> stats = new LinkedHashMap<>();

        // 获取总请求量
        long totalCount = apiLogMapper.selectCount(null);
        stats.put("totalRequests", totalCount);

        // 获取最近1小时请求量
        long lastHourCount = apiLogMapper.selectCount(new QueryWrapper<ApiLog>()
                .ge("request_time", Date.from(Instant.now().minus(1, ChronoUnit.HOURS))));
        stats.put("lastHourRequests", lastHourCount);

        // 获取TOP 10请求路径
        stats.put("topRequests", getTop10Requests());

        // 错误率统计
        long errorCount = apiLogMapper.selectCount(new QueryWrapper<ApiLog>()
                .ge("status_code", 400)); // 400及以上都算错误
        stats.put("errorRate", totalCount == 0 ? 0 : (double) errorCount / totalCount);

        return stats;
    }

    private List<Map<String, Object>> getTop10Requests() {
        return apiLogMapper.selectMaps(new QueryWrapper<ApiLog>()
                .select("path, COUNT(*) as count")
                .groupBy("path")
                .orderByDesc("count")
                .last("LIMIT 10"));
    }
}